/*
 * @描述: 
 * @创建者: kilomChou
 * @Date: 2021-04-11 17:21:46
 * @最后编辑: kilomChou
 * @LastEditTime: 2021-05-15 11:43:16
 */
import { RandUtil } from "../../util/RandUtil";
import BaseAI, { IBaseAI } from "./BaseAI";
import SnakeNode from "../snake/SnakeNode";
import { ICircle, Vec2 } from "../../core/vec2/Vec2";
import Vec2Operator from "../../core/vec2/Vec2Operator";
const [v2, v2op] = [Vec2, new Vec2Operator()];

/** 智能躲蛇 */
export default class AIAwaySnake extends BaseAI {

    constructor(obj: IAIAwaySnake) {
        super(obj)
        this._checkDistance = this.toMinMax(obj.checkDistance)
    }

    private _checkDistance: number[]
    private _checkDis!: number

    getKey(): string { return "ai_away_snake" + this.snake.id }

    aiStart() {
        let head = this.head
        this._checkDis = RandUtil.rand2(this._checkDistance) * head.w + head.w
        let checkCol = v2op.setObj(tmpCIr).posAs(head).setR(this._checkDis * 0.5);
        let chunks = this.world.getChunks(checkCol.obj)
        let nodes = this.world.getSnakeNodesExclude(chunks, [this.snake])

        if (!nodes.some(node => checkCol.isColCir(node))) {
            this.recheck()
        }
    }

    ai(dt: number): void {

        let head = this.head
        let awayNode!: SnakeNode
        let minDis: number = Number.MAX_SAFE_INTEGER
        let checkCol = v2op.setObj(tmpCIr).posAs(head).setR(this._checkDis * 0.5);
        let chunks = this.world.getChunks(checkCol.obj)
        let nodes = this.world.getSnakeNodesExclude(chunks, [this.snake])

        nodes.forEach(node => {
            //找到检测范围内的最近的蛇节点
            if (checkCol.isColCir(node)) {
                let dis = checkCol.dis(node)
                if (dis < minDis) {
                    minDis = dis
                    awayNode = node
                }
            }
        })

        if (awayNode) {
            this.aiVal.nearestNode = awayNode;
            this.snake.toAng = v2.angTo(awayNode, head);
        } else {
            this.recheck()
        }
    }

    aiStop() {
        this.aiVal.nearestNode = null!
    }

}

export interface IAIAwaySnake extends IBaseAI {
    checkDistance: number | [number, number]
}

const tmpCIr: ICircle = { x: 0, y: 0, r: 0 };